<?php

namespace app\macht\controller;

use app\common\controller\Balance;
use app\common\controller\Balancet;
use app\common\controller\Bonus;
use app\common\controller\BonusT;
use app\common\controller\CardPut;
use app\common\controller\Helpinfo;
use app\common\controller\Platurl;
use app\common\controller\TemplateMsg;
use app\common\model\CardBonusRule;
use app\common\model\CardConsume;
use app\common\model\CardCzLog;
use app\common\model\CardFans;
use app\common\model\CardGivecardLog;
use app\common\model\CardGivePutCard;
use app\common\model\CardMember;
use app\common\model\CardPaycardlog;
use app\common\model\CardQrcode;
use app\common\model\CardUrlDict;
use app\common\model\CardUserGet;
use app\common\model\CardRank;
use app\common\model\Agent;
use app\common\model\CardUserGetAli;
use app\common\model\CardUserMarkLog;
use app\common\model\CardUserUpdate;
use app\common\model\CardCzgive;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use app\common\model\Momerchant;
use app\common\model\Merchant;
use app\common\model\System;
use app\common\controller\Carddate;
use app\common\controller\AdminBase;
use app\mobile\controller\Cardextend;
use Composer\Autoload\includeFile;
use think\Config;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Cardusold extends MachBase
{



    //领取列表
    public function getlistsold($type = '')
    {
        $CardUserGet = new CardUserGet();
        $Merchant = new Merchant();
        $p_data = request()->get();
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            if ($p_data['nickname']) {
                $map['nickname'] = array('like', '%' . trim($p_data['nickname']) . '%');
            } else {
                $p_data['nickname'] = '';
            }
            if ($p_data['code']) {
                $map['code|phone|old_code'] = array('like', '%' . trim($p_data['code']) . '%');
            } else {
                $p_data['code'] = '';
            }
            if ($p_data['fire']) {
                $map['fire'] = $p_data['fire'];
            } else {
                //激活状态
                if (isset($p_data['fire'])) {
                    if ($p_data['fire'] == 0 && $p_data['fire'] <> '') {
                        $map['fire'] = 0;
                    }
                }
                //END
                $p_data['fire'] = '';
            }
            //积分筛选
            if ($p_data['bonus_scr']) {
                $ord['bonus'] = $p_data['bonus_scr'] == 1 ? 'desc' : 'asc';
            } else {
                $p_data['bonus_scr'] = '';

            }
            //余额筛选
            if ($p_data['balance_scr']) {
                $ord['balance'] = $p_data['balance_scr'] == 1 ? 'desc' : 'asc';
            } else {
                $p_data['balance_scr'] = '';
            }
            //时间筛选
            if ($p_data['get_scr']) {
                $ord['create_time'] = $p_data['get_scr'] == 1 ? 'asc' : 'desc';
            } else {
                $p_data['get_scr'] = '';
            }
            $ord['id'] = 'desc';
        } else {
            $p_data['nickname'] = '';
            $p_data['code'] = '';
            $p_data['fire'] = '';
            $p_data['bonus_scr'] = '';
            $p_data['balance_scr'] = '';
            $p_data['get_scr'] = '';
            $ord['id'] = 'asc';
            $map['fire'] = '1';
        }
        $map['card_type'] = ['eq', 'MEMBER_CARD'];
        $map['statu'] = 0;
        if ($type !== '') {
            $map['have'] = $type;
        } else {
            $map['have'] = 1;
        }
        $CardMember = new CardMember();
        $card_id = $CardMember->where(['top_mid' => Session::get('login_top_mid')])->value('card_id');
        $map['card_id'] = $card_id;
        $list = $CardUserGet->where($map)->order($ord)->paginate('20', false, ['query' => request()->param()]);
        $carduser['num'] = $CardUserGet->where($map)->count('id');
        foreach ($list as $k => $v) {
            if (Session::get('login_top_mid') == 1) {
                $list[$k]['phone']="演示后台不展示此项";
            }
        }
        $carduser['count'] = $CardUserGet->where(['card_id' => $card_id])->count('id');
        $carduser['notfire'] = $CardUserGet->where(['card_id' => $card_id, 'fire' => 0])->count('id');
        $carduser['fire'] = $CardUserGet->where(['card_id' => $card_id, 'fire' => 1])->count('id');
        $carduser['nothave'] = $CardUserGet->where(['card_id' => $card_id, 'have' => 0])->count('id');
        $card['card_id'] = $card_id;
        $card['type'] = $type;
        $mab['id'] = array('in', $this->get_mer_mid());
        $mach = $Merchant->where($mab)->select();
        $user = Session::get('user');
        //充值规则
        $CardCzgive = new CardCzgive();
        $maps['card_id'] = $card_id;
        $maps['statu'] = 1;
        $czgive = $CardCzgive->where($maps)->select();
        $this->assign('czgive', $czgive);
        $this->assign('carduser', $carduser);
        $this->assign('card', $card);
        $this->assign('p_data', $p_data);
        $this->assign('list', $list);
        $this->assign('mach', $mach);
        $this->assign('user', $user);
        return $this->fetch();
    }






    //会员卡详情
    public function getcardusinfoold()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardMember = new CardMember();
            $map['id'] = $arr['id'];
            $map['top_mid'] = Session::get('login_top_mid');
            $info = $CardMember->where($map)->find();
            return json($info);
        }
    }

    //领取会员详情
    public function getCardInfoold()
    {
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardUserGet = new CardUserGet();
            $map['id'] = $arr['id'];
            $user = $CardUserGet->where($map)->find();
            return json($user);
        }
    }


    //领取会员修改
    public function edituserinfoold()
    {
        $CardUserGet = new CardUserGet();
        if (Request()->isPost()) {
            $id = request()->param('id');
            $arr = request()->post();
            $data = $arr;
            $res = $CardUserGet->save($data, ['id' => $id]);
            if ($res) {
                $this->success('修改成功', url('cardus/edituserinfo', ['id' => $id]));
            } else {
                $this->error('修改失败', url('cardus/edituserinfo', ['id' => $id]));
            }
        } else {
            $id = request()->param('id');
            $map['id'] = $id;
            $user = $CardUserGet->where($map)->find();
            if (Session::get('login_top_mid') == 1) {
                $user['phone']="";
            }
            $this->assign('user', $user);
            return $this->fetch();
        }
    }



    //获取激活信息
    public function getcardinfosold()
    {
        if (Session::get('login_top_mid') == 1) {
            $this->error('演示后台未开启此功能');
        }
        $arr = request()->param();
        $CardUserGet = new CardUserGet();
        $map['id'] = $arr['id'];
        $user = $CardUserGet->where($map)->find();
        $options = $this->options($user['card_id']);
        $WxObj = new Wxobjopen($options);
        $data['code'] = $user['code'];
        $data['card_id'] = $user['card_id'];
        $res = $WxObj->userGetInfo($data);
        return json($res);
    }



    //获取本会员余额变动详情
    public function cardusbalanceold(){
        $get_id = request()->param('get_id');
        $CardUserGet = new CardUserGet();
        $CardUserUpdate = new CardUserUpdate();
        $p_data = request()->get();
        unset($p_data['page']);
        unset($p_data['card_id']);
        unset($p_data['get_id']);
        if ($p_data) {
            if ($p_data['type'] != ''){
                $map['type'] = $p_data['type'];
            }
            if ($p_data['hx_fs'] !=''){
                $map['hx_fs'] = $p_data['hx_fs'];
            }
            if ($p_data['starttime'] !== '') {
                $starttime = strtotime($p_data['starttime']);
            } else {
                $starttime = 0;
            }
            if ($p_data['endtime'] !== '') {
                $endtime = strtotime($p_data['endtime'])+86399;
            } else {
                $endtime = strtotime(date('Y-m-d H:i:s'));
            }
            $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        } else {
            $p_data['type'] = ['in',['1,2']];
            $p_data['starttime'] = '';
            $p_data['endtime'] = '';
            $p_data['hx_fs'] = '请选择';
        }
        $arr  = $CardUserGet->where('id',$get_id)->field('openid,card_id,code')->find();
        $map['openid'] = $arr['openid'];
        $map['card_id'] = $arr['card_id'];
        $map['code'] = $arr['code'];
        $map['add_balance|del_balance'] = ['neq',0];

        $list = $CardUserUpdate->where($map)->order('id desc')->paginate(15,false,['query' => request()->param()]);
//        var_dump($CardUserUpdate->getLastSql());
        $this->assign('list',$list);
        $this->assign('p_data',$p_data);
        return $this->fetch();
    }



    /*
     *Carduser 中操作
     *
     */
    //获取会员基本信息
    /*
     * id
     */
    public function getcarduserinfoold(){
//        if (Request()->isAjax()){
        $arr = request()->post();
        $CardUserGet = new CardUserGet();
        $user = [];
        $user['user'] = $CardUserGet->where(array('id'=>$arr['id']))->field('bonus,email,balance,mid,top_mid,card_id,sex,code,outerstr,nickname,name,phone,have,address,fire,openid,birthday,create_time')->find();
        $user['user']['merchant'] = getmerchant($user['user']['mid']);
        $user['user']['zodiac'] = $this->getuserzodiac($user['user']['birthday']);
        $user['user']['level'] = getlivename($user['user']['card_id'],$user['user']['bonus']);
        $user['user']['age'] = $this->userage($user['user']['birthday']);
        $user['user']['is_follow'] = getfollowstatu($user['user']['openid']);
        $user['user']['sharename'] = getsharename($user['user']['outerstr']);
        $user['user']['sex'] =$user['user']['sex'] == 1?'男':'女';
        $user['cards'] = $this->getcardsnum($user['user']);

        $arr['openid'] = $user['user']['openid'];
        $user['wxinfo'] = $this->getwxfansinfo($arr);
        if ($user){
            $rarr = ['code'=>0,'message'=>'SUCCESS','data'=>$user];
        }else{
            $rarr = ['code'=>9001,'message'=>'未找到'];
        }
        return json($rarr);
//        }
    }


    //修改会员  remark
    public function getcardusereditold(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            $data['birthday'] = $arr['birthday'];
            $data['email'] = $arr['email'];
            $data['name'] = $arr['name'];
            $data['nickname'] = $arr['nickname'];
            $data['phone'] = $arr['phone'];
            $data['sex'] = $arr['sex'];
            $data['remark'] = $arr['remark'];
            $data['update_time'] = time();
            $map['code'] = $arr['code'];
            $map['openid'] = $arr['openid'];
            $CardUserGet = new CardUserGet();
            $res = $CardUserGet->allowField(true)->save($data,$map);
            if ($res){
                $rs = $this->rec_mark($map);
                $rarr = ['code'=>0,'message'=>'修改成功','re'=>$rs,'data'=>$data];

            }else{
                $rarr = ['code'=>9001,'message'=>'修改失败','sql'=>$CardUserGet->getLastSql(),'arr'=>$arr];
            }
            return json($rarr);
        }
    }

    //备注记录
    private function rec_mark($map){
        $CardUserGet = new CardUserGet();
        $user = $CardUserGet->where($map)->field('code,card_id,mid,remark,openid')->find();
        $CardUserMarkLog = new CardUserMarkLog();
        $data['code'] = $user['code'];
        $data['card_id'] = $user['card_id'];
        $data['mid'] = $user['mid'];
        $data['con_username'] = Session::get('user.nickname');
        $data['remark'] = $user['remark'];
        $data['openid'] = $user['openid'];
        $data['create_time'] = time();
        $s = $CardUserMarkLog->allowField(true)->save($data);
        return $s;
    }

    //备注记录
    public function getremarklistold(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardUserMarkLog = new CardUserMarkLog();
            $page=($arr['page']-1)*10;
            $map['openid'] = $arr['openid'];
            $map['code'] = $arr['code'];
            $list = $CardUserMarkLog->where($map)->limit($page,10)->order('create_time','desc')->select();
            $count = $CardUserMarkLog->where($map)->count();
            if ($list){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $list;
                $data['conut'] = $count;
                $data['page'] = $arr['page'];
                $data['pagenum'] = ceil($count/10);
            }else{
                $data['code'] = 9001;
                $data['message'] = 'ERROR';
                $data['data'] = '';
            }
            return json($data);
        }
    }

    //获取消费信息
    /*
     * openid  code  top_mid
     */
    public function getcarduserxfinfoold(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardUserUpdate = new CardUserUpdate();
            //消费统计
            $map['openid'] = $arr['openid'];
            $map['code'] = $arr['code'];
            $pay_balance = $CardUserUpdate->where($map)->sum('pay_balance');   //应付金额
            $xfcount['del_balance'] = $CardUserUpdate->where($map)->sum('del_balance');   //消费金额
            $xfcount['add_balance'] = $CardUserUpdate->where($map)->sum('add_balance');   //充值金额
            $xfcount['add_bonus'] = $CardUserUpdate->where($map)->sum('add_bonus');   //累计获得积分
            $xfcount['del_bonus'] = $CardUserUpdate->where($map)->sum('del_bonus');   //累计使用积分
            $map['del_balance'] = ['neq',0];
            $xfcount['xf_nume'] = $CardUserUpdate->where($map)->count();   //消费笔数
            unset($map['del_balance']);
            //消费笔数END
            $map['add_balance'] = ['neq',0];
            $xfcount['cz_nume'] = $CardUserUpdate->where($map)->count();   //充值笔数
            unset($map['add_balance']);
            //充值笔数END
            $map['top_mid'] = $arr['top_mid'];
            $maps = $map;
            unset($maps['code']);
            $xfcount['get_cards'] = $this->getcardsnum($maps);;   //累计获得卡券
            //消费统计END
            //最近消费
            unset($map['top_mid']);
            $xfjl = $CardUserUpdate->where($map)->order('create_time desc')->limit(1)->select();
            if ($xfjl){
                $zjxf = $xfjl[0];
            }else{
                $zjxf = ['mid'=>0,'del_balance'=>0,'create_time'=>0];
            }
            $lately['merchant'] = getmerchant($zjxf['mid']);        //最近消费门店
            $lately['pay_balance'] = $zjxf['del_balance'];        //最近消费金额\
            $lately['pay_time'] = $zjxf['create_time'] == 0?'无':$zjxf['create_time'];        //最近消费时间    $zjxf['create_time'] == 0?'无':
            //最近消费END
            //平均消费
            $average['del_balance'] = $xfcount['del_balance'] == 0?'0':$xfcount['del_balance']/ $xfcount['xf_nume'];        //平均消费
            $average['add_balance'] = $xfcount['add_balance'] == 0?'0':$xfcount['add_balance']/ $xfcount['cz_nume'];        //平均充值
            $average['discount'] = $pay_balance == 0?'0':$pay_balance/$xfcount['del_balance'];                   //平均折扣
            //平均消费END
            //返回值
            $data['code'] = 0;
            $data['message'] = 'SUCCESS';
            $data['xfcount'] = $xfcount;        //消费统计
            $data['lately'] = $lately;          //最近消费
            $data['average'] = $average;          //平均消费
            //返回值END
            return json($data);
        }
    }

    //获取消费记录
    /*
     * openid  code
     */
    public function getcarduserxflistold(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardUserUpdate = new CardUserUpdate();
            $page=($arr['page']-1)*10;
            $map['openid'] = $arr['openid'];
            $map['code'] = $arr['code'];
            $map['del_balance'] = ['neq',0];
            $list = [];
            $list = $CardUserUpdate->where($map)->limit($page,10)->order('create_time','desc')->select();
            foreach ($list as $k=>$v){
                $list[$k]['merchant'] = getmachname($v['mid']);
            }
            $count = $CardUserUpdate->where($map)->count();
            if ($list){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $list;
                $data['conut'] = $count;
                $data['page'] = $arr['page'];
                $data['pagenum'] = ceil($count/10);
            }else{
                $data['code'] = 9001;
                $data['message'] = 'ERROR';
                $data['data'] = '';
            }
            return json($data);
        }
    }

    //获取充值记录
    /*
     * openid  code
     */
    public function getcarduserczlistold(){
        if (Request()->isAjax()) {
            $arr = request()->post();
//            return json($arr);
            $CardUserUpdate = new CardUserUpdate();
            $page=($arr['page']-1)*10;
            $map['openid'] = $arr['openid'];
            $map['code'] = $arr['code'];
            $map['add_balance'] = ['neq',0];
            $list = $CardUserUpdate->where($map)->limit($page,10)->order('create_time','desc')->select();
            foreach ($list as $k=>$v){
                $list[$k]['merchant'] = getmachname($v['mid']);
                $list[$k]['pay_fs'] = getpayfs($v['hx_fs']);
            }
            $count = $CardUserUpdate->where($map)->count();
            if ($list){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $list;
                $data['conut'] = $count;
                $data['page'] = $arr['page'];
                $data['pagenum'] = ceil($count/10);
            }else{
                $data['code'] = 9001;
                $data['message'] = 'ERROR';
                $data['data'] = '';
            }
            return json($data);
        }
    }

    //获取积分记录
    /*
     * openid  code
     */
    public function getcarduserbonuslistold(){
        if (Request()->isAjax()) {
            $arr = request()->post();
            $CardUserUpdate = new CardUserUpdate();
            $page=($arr['page']-1)*10;
            $map['openid'] = $arr['openid'];
            $map['code'] = $arr['code'];
            $map['add_bonus|del_bonus'] = ['neq',0];
            $list = $CardUserUpdate->where($map)->limit($page,10)->order('create_time','desc')->select();
            $count = $CardUserUpdate->where($map)->count();
            if ($list){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $list;
                $data['conut'] = $count;
                $data['page'] = $arr['page'];
                $data['pagenum'] = ceil($count/10);
            }else{
                $data['code'] = 9001;
                $data['message'] = 'ERROR';
                $data['data'] = '';
            }
            return json($data);
        }
    }

    //获取卡券记录
    /*
     * openid  top_mid
     */
    public function getcardusercardslistold(){
        if (Request()->isAjax()){
            $arr = request()->post();
            $CardUserGet = new CardUserGet();
            $page=($arr['page']-1)*10;
            $map['openid'] = $arr['openid'];
            $map['top_mid'] = $arr['top_mid'];
            $map['card_type'] = ['neq','MEMBER_CARD'];
            $list = $CardUserGet->where($map)->limit($page,10)->order('create_time','desc')->select();
            foreach ($list as $k=>$v){
                $list[$k]['card_type'] = getcardtype($v['card_type']);
                $list[$k]['title'] = cardgetinfo($v['card_id'],1,1);
                $list[$k]['merchant'] = getmachname($v['mid']);
                $list[$k]['card_statu'] = $v['statu']==0?'未使用':'已使用';
            }
            $count = $CardUserGet->where($map)->count();
            if ($list){
                $data['code'] = 0;
                $data['message'] = 'SUCCESS';
                $data['data'] = $list;
                $data['conut'] = $count;
                $data['page'] = $arr['page'];
                $data['pagenum'] = ceil($count/10);

            }else{
                $data['code'] = 9001;
                $data['message'] = 'ERROR';
                $data['data'] = '';
            }
            return json($data);
        }

    }



    //获取所属微信信息
    /*
     * OPENID
     */
    private function getwxfansinfo($arr){
        $CardFans = new CardFans();
        $info = $CardFans->where(['openid'=>$arr['openid']])->field('head_url,sex,city,province,country')->find();
        $info['sex'] = $info['sex'] == 1?'男':'女';
        return $info;
//        if ($info){
//            $data['code'] = 0;
//            $data['message'] = 'SUCCESS';
//            $data['data'] = $info;
//        }else{
//            $data['code'] = 9001;
//            $data['message'] = 'ERROR';
//            $data['data'] = '';
//        }
    }

    //获取卡券总数
    private function getcardsnum($arr){
//        return $arr;
        $CardUserGet = new CardUserGet();
        $map['openid'] = $arr['openid'];
        $map['top_mid'] = $arr['top_mid'];
        $map['card_type'] = ['neq','MEMBER_CARD'];
        $num = $CardUserGet->where($map)->count();   //累计获得卡券
        return $num;
    }

    //获取生日所属星座
    private function getuserzodiac($birthday){
        if (!$birthday){return 'null';}
        $month = intval(substr($birthday, 5, 2));
        $day = intval(substr($birthday, 8, 2));
        if ($month < 1 || $month > 12 || $day < 1 || $day > 31)
        {
            return NULL;
        }
        $signs = array(
            array('20' => '水瓶座'),
            array('19' => '双鱼座'),
            array('21' => '白羊座'),
            array('20' => '金牛座'),
            array('21' => '双子座'),
            array('22' => '巨蟹座'),
            array('23' => '狮子座'),
            array('23' => '处女座'),
            array('23' => '天秤座'),
            array('24' => '天蝎座'),
            array('22' => '射手座'),
            array('22' => '摩羯座')
        );
        list($start, $name) = each($signs[$month - 1]);
        if ($day < $start)
        {
            list($start, $name) = each($signs[($month - 2 < 0) ? 11 : $month - 2]);
        }

        return $name;
    }

    //计算年龄
    private function userage($birthday){
        if (!$birthday){return 'null';}
        list($year,$month,$day) = explode("-",$birthday);
        $year_diff = date("Y") - $year;
        $month_diff = date("m") - $month;
        $day_diff  = date("d") - $day;
        if ($day_diff < 0 || $month_diff < 0)
            $year_diff--;
        return $year_diff;
    }



    //获取本会员卡券核销详情
    public function cardsconsumeold(){
        $arr = request()->param();
        $CardConsume = new CardConsume();
        $map['openid'] = $arr['openid'];
        $map['card_id'] = $arr['card_id'];
        $map['code'] = $arr['code'];
        $list = $CardConsume->where($map)->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    //会员卡核销详情
    public function reportcardmemberold(){
        $CardUserUpdate = new CardUserUpdate();
        $CardMember = new CardMember();
        $request = request();
        //未创建门店
        if ($this->get_mer_mid() !== ''){
            $mid = $this->get_mer_mid();
        }else{
            $mid = null;
        }
        $p_data = $request->get();
        unset($p_data['page']);
        unset($p_data['card_id']);
        if ($p_data) {
            if ($p_data['mid'] != ''){
                $mid = $p_data['mid'];
            }
        } else {
            $p_data['mid'] = '';
        }
        //会员卡列表
        if ($this->get_mer_mid() !== '') {
            $map['mid'] = ['in', $this->get_mer_mid()];
        }else{
            $map['mid'] = null;
        }
        $list = $CardMember->where($map)->paginate(10);
        //今日统计
        $today = strtotime(date("Y-m-d"),time());
        $enday = $today+86399;
        $day['create_time'] = ['between',[$today,$enday]];
        $day['mid'] = ['in', $mid];
        $day['type'] = 2;
        //本周统计
        $toweek = strtotime(date('Y-m-d', strtotime("this week Monday", time())));
        $enweek =  strtotime(date('Y-m-d', strtotime("this week Sunday", time()))) + 24 * 3600 - 1;
        $week['create_time'] = ['between',[$toweek,$enweek]];
        $week['mid'] = ['in', $mid];
        $week['type'] = 2;
        //本月统计
        $tomonth =mktime(0, 0, 0, date('m'), 1, date('Y'));
        $enmonth =mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        $month['create_time'] = ['between',[$tomonth,$enmonth]];
        $month['mid'] = ['in', $mid];
        $month['type'] = 2;
        //数据输出
        //日
        $daysum['numsum'] = $CardUserUpdate->where($day)->count('id');
        $daysum['bonsum'] = $CardUserUpdate->where($day)->sum('del_bonus');
        $daysum['balsum'] = $CardUserUpdate->where($day)->sum('del_balance');
        //周
        $weeksum['numsum'] = $CardUserUpdate->where($week)->count('id');
        $weeksum['bonsum'] = $CardUserUpdate->where($week)->sum('del_bonus');
        $weeksum['balsum'] = $CardUserUpdate->where($week)->sum('del_balance');
//        dump($week);
        //月
        $monthsum['numsum'] = $CardUserUpdate->where($month)->count('id');
        $monthsum['bonsum'] = $CardUserUpdate->where($month)->sum('del_bonus');
        $monthsum['balsum'] = $CardUserUpdate->where($month)->sum('del_balance');
        if ($mid == ''){
            //日
            $daysum['numsum'] = '';
            $daysum['bonsum'] = '';
            $daysum['balsum'] = '';
            //周
            $weeksum['numsum'] = '';
            $weeksum['bonsum'] = '';
            $weeksum['balsum'] = '';
            //月
            $monthsum['numsum'] = '';
            $monthsum['bonsum'] = '';
            $monthsum['balsum'] = '';
        }
        $Merchant = new Merchant();
        $mab['id'] = ['in',$this->get_mer_mid()];
        $mach = $Merchant->where($mab)->select();
        $this->assign('mach',$mach);
        $this->assign('daysum',$daysum);
        $this->assign('weeksum',$weeksum);
        $this->assign('monthsum',$monthsum);
        $this->assign('p_data',$p_data);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //会员卡统计概览
    public function cardsurveyold($card_id=''){
        $request = request();
        $p_data = $request->get();
        //搜索条件
        unset($p_data['page']);
        unset($p_data['card_id']);
        if ($p_data) {
            if ($p_data['code'] != ''){
                $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
            }
            if ($p_data['mid'] != ''){
                $map['mid'] = $p_data['mid'];
            }else{
                if($this->get_mer_mid() !== ''){
                    $map['mid'] = ['in',$this->get_mer_mid()];
                }else{
                    $map['mid'] = null;
                }
            }
            if ($p_data['con_username'] != ''){
                $map['con_username'] = array('like', '%' . trim($p_data['con_username']) . '%');
            }
            if ($p_data['min_balance'] !== '') {
                $min_balance = $p_data['min_balance'];
            } else {
                $min_balance = 0;
            }
            if ($p_data['max_balance'] !== '') {
                $map['add_balance'] = array('between', "" . $min_balance . "," . $p_data['max_balance'] . "");
            } else {
                $map['add_balance'] = array('egt', $p_data['min_balance']);
            }
            if ($p_data['starttime'] !== '') {
                $starttime = strtotime($p_data['starttime']);
            } else {
                $starttime = 0;
            }
            if ($p_data['endtime'] !== '') {
                $endtime = strtotime($p_data['endtime']) + 86400;
            } else {
                $endtime = strtotime(date('Y-m-d H:i:s'));
            }
            $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        } else {
            $p_data['max_balance'] = '';
            $p_data['min_balance'] = '';
            $p_data['code'] = '';
            $p_data['mid'] = '';
            $p_data['con_username'] = '';
            $p_data['starttime'] = '';
            $p_data['endtime'] = '';
            if($this->get_mer_mid() !== ''){
                $map['mid'] = ['in',$this->get_mer_mid()];
            }else{
                $map['mid'] = null;
            }
        }
        if (empty($card_id)){
        }else{
            $map['card_id'] = ['eq',$card_id];
        }
        if($this->get_mer_mid() !== ''){
            $mid = ['in',$this->get_mer_mid()];
        }else{
            $mid = null;
        }
        $add_balance['mid'] = $mid;
        $add_balance['add_balance & pay_balance'] = ['neq',0];
        $add_balance['del_balance'] = 0;
        $CardUserUpdate = new CardUserUpdate();
        $CardUserGet = new CardUserGet();
        $survey['total_balance'] = $CardUserUpdate->where($add_balance)->sum('add_balance');     //总金额
        $del_balance['mid'] = $mid;
        $del_balance['type'] = 2;
//        $del_balance['add_balance & pay_balance'] = ['eq',0];
        $del_balance['del_balance'] = ['>',0];
        $del_balance['cate'] = ['in',[2,3]];;
        $survey['consum_balance'] = $CardUserUpdate->where($del_balance)->sum('del_balance');       //消费额

        $survey['surplus_balance'] = $survey['total_balance'] - $survey['consum_balance'];                          //剩余额度
        $maps['card_id'] = $this->get_card_id();
        $survey['surplus_bonus'] = $CardUserGet->where($maps)->sum('bonus');                  //剩余积分
//        var_dump($CardUserGet->getLastSql());
        $this->get_machlist();

        $map['add_balance|pay_balance|del_balance'] = ['neq',0];
        $list = $CardUserUpdate->where($map)->order('id desc' )->paginate('20',false,['query' => request()->param()]);
//        var_dump($CardUserUpdate->getLastSql());
        $this->assign('p_data',$p_data);
        $this->assign('survey',$survey);
        $this->assign('list',$list);
        return $this->fetch();
    }


    //获取card_id
    private function get_card_id(){
        $CardMerchant = new CardMember();
        $card_id = $CardMerchant->where(['top_mid'=>Session::get('login_top_mid')])->value('card_id');
        return $card_id;
    }

    //会员卡核销记录
    public function reportcardmemberlistold($card_id=''){
        $request = request();
        $p_data = $request->get();
        //搜索条件
        unset($p_data['page']);
        unset($p_data['card_id']);
        if ($p_data) {
            if ($p_data['code'] != ''){
                $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
            }
            if ($p_data['mid'] != ''){
                $map['mid'] = array('like', '%' . trim($p_data['mid']) . '%');
            }else{
                if($this->get_mer_mid() !== ''){
                    $map['mid'] = ['in',$this->get_mer_mid()];
                }else{
                    $map['mid'] = null;
                }
            }
            if ($p_data['con_username'] != ''){
                $map['con_username'] = array('like', '%' . trim($p_data['con_username']) . '%');
            }
            if ($p_data['min_balance'] !== '') {
                $min_balance = $p_data['min_balance'];
            } else {
                $min_balance = 0;
            }
            if ($p_data['max_balance'] !== '') {
                $map['del_balance'] = array('between', "" . $min_balance . "," . $p_data['max_balance'] . "");
            } else {
                $map['del_balance'] = array('egt', $p_data['min_balance']);
            }
            if ($p_data['starttime'] !== '') {
                $starttime = strtotime($p_data['starttime']);
            } else {
                $starttime = 0;
            }
            if ($p_data['endtime'] !== '') {
                $endtime = strtotime($p_data['endtime']) + 86400;
            } else {
                $endtime = strtotime(date('Y-m-d H:i:s'));
            }
            $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        } else {
            $p_data['max_balance'] = '';
            $p_data['min_balance'] = '';
            $p_data['code'] = '';
            $p_data['mid'] = '';
            $p_data['con_username'] = '';
            if($this->get_mer_mid() !== ''){
                $map['mid'] = ['in',$this->get_mer_mid()];
            }else{
                $map['mid'] = null;
            }
        }
        if (empty($card_id)){
        }else{
            $map['card_id'] = ['eq',$card_id];
        }
        $map['type'] = 2;
        //数据搜索
        $CardUserUpdate = new CardUserUpdate();
        //今日统计
        $today = strtotime(date("Y-m-d"),time());
        $enday = $today+86399;
        $day['create_time'] = ['between',[$today,$enday]];
//        $day['card_id'] = $map['card_id'];
        $day['mid'] = $map['mid'];
        $day['type'] = 2;
        //本周统计
        $toweek = strtotime(date('Y-m-d', strtotime("this week Monday", time())));
        $enweek =  strtotime(date('Y-m-d', strtotime("this week Sunday", time()))) + 24 * 3600 - 1;
        $week['create_time'] = ['between',[$toweek,$enweek]];
//        $week['card_id'] = $map['card_id'];
        $week['mid'] = $map['mid'];
        $week['type'] = 2;
        //本月统计
        $tomonth =mktime(0, 0, 0, date('m'), 1, date('Y'));
        $enmonth =mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        $month['create_time'] = ['between',[$tomonth,$enmonth]];
//        $month['card_id'] = $map['card_id'];
        $month['mid'] = $map['mid'];
        $month['type'] = 2;
        //数据输出
        //日
        $daysum['numsum'] = $CardUserUpdate->where($day)->count('id');              //数量
        $daysum['del_balsum'] = $CardUserUpdate->where($day)->sum('del_balance');   //核销额
        //周
        $weeksum['numsum'] = $CardUserUpdate->where($week)->count('id');            //数量
        $weeksum['del_balsum'] = $CardUserUpdate->where($week)->sum('del_balance'); //核销额
        //月
        $monthsum['numsum'] = $CardUserUpdate->where($month)->count('id');              //数量
        $monthsum['del_balsum'] = $CardUserUpdate->where($month)->sum('del_balance');   //核销额
//        var_dump($CardUserUpdate->getLastSql());
//        var_dump($month);
        $map['del_balance|pay_balance'] = ['neq',0];
        $list = $CardUserUpdate->where($map)->order('id desc' )->paginate('20',false,['query' => request()->param()]);
        //门店
        $Merchant = new Merchant();
        $mab['id'] = ['in',$this->get_mer_mid()];
        $mach = $Merchant->where($mab)->select();
        $this->assign('mach',$mach);
        $this->assign('daysum',$daysum);        //日
        $this->assign('weeksum',$weeksum);      //周
        $this->assign('monthsum',$monthsum);    //月
        $this->assign('p_data',$p_data);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //会员卡充值记录
    public function cardreglistold($card_id=''){
        $request = request();
        $p_data = $request->get();
        //搜索条件
        unset($p_data['page']);
        unset($p_data['card_id']);
        if ($p_data) {
            if ($p_data['code'] != ''){
                $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
            }
            if ($p_data['mid'] != ''){
                $map['mid'] = array('like', '%' . trim($p_data['mid']) . '%');
            }else{
                if($this->get_mer_mid() !== ''){
                    $map['mid'] = ['in',$this->get_mer_mid()];
                }else{
                    $map['mid'] = null;
                }
            }
            if ($p_data['con_username'] != ''){
                $map['con_username'] = array('like', '%' . trim($p_data['con_username']) . '%');
            }
            if ($p_data['min_balance'] !== '') {
                $min_balance = $p_data['min_balance'];
            } else {
                $min_balance = 0;
            }
            if ($p_data['max_balance'] !== '') {
                $map['add_balance'] = array('between', "" . $min_balance . "," . $p_data['max_balance'] . "");
            } else {
                $map['add_balance'] = array('egt', $p_data['min_balance']);
            }
            if ($p_data['starttime'] !== '') {
                $starttime = strtotime($p_data['starttime']);
            } else {
                $starttime = 0;
            }
            if ($p_data['endtime'] !== '') {
                $endtime = strtotime($p_data['endtime']) + 86400;
            } else {
                $endtime = strtotime(date('Y-m-d H:i:s'));
            }
            $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        } else {
            $p_data['max_balance'] = '';
            $p_data['min_balance'] = '';
            $p_data['code'] = '';
            $p_data['mid'] = '';
            $p_data['con_username'] = '';
            $p_data['starttime'] = '';
            $p_data['endtime'] = '';
            if($this->get_mer_mid() !== ''){
                $map['mid'] = ['in',$this->get_mer_mid()];
            }else{
                $map['mid'] = null;
            }
        }
        if (empty($card_id)){
        }else{
            $map['card_id'] = ['eq',$card_id];
        }
        $map['type'] = 1;
        $CardUserUpdate = new CardUserUpdate();
        //数据统计
        //今日统计

        $map['add_balance & pay_balance'] = ['neq',0];
        $map['del_balance'] = 0;
        $count['num_sum'] = $CardUserUpdate->where($map)->count('id');              //数量
        $count['pay_balsum'] = $CardUserUpdate->where($map)->sum('pay_balance');   //支付额
        $count['total_balsum'] = $CardUserUpdate->where($map)->sum('add_balance');   //增加额
//        $count['total_balsum'] = 0;
        $count['give_balsum'] = $count['total_balsum'] - $count['pay_balsum'];
        //数据搜索
//        var_dump(json_encode($count,JSON_UNESCAPED_UNICODE));
        $list = $CardUserUpdate->where($map)->order('id desc' )->paginate('20',false,['query' => request()->param()]);
        //门店
        $Merchant = new Merchant();
        $mab['id'] = ['in',$this->get_mer_mid()];
        $mach = $Merchant->where($mab)->select();
//        $this->assign('daysum',$daysum);        //日
//        $this->assign('weeksum',$weeksum);      //周
        $this->assign('count',$count);    //统计
        $this->assign('mach',$mach);
        $this->assign('p_data',$p_data);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //积分数据
    public function cardbonuslistold(){
        $p_data = request()->get();
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            if ($p_data['code']) {
                $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
            } else {
                $p_data['code'] = '';
            }
            //门店
            if ($p_data['mid']){
                $map['mid'] = $p_data['mid'];
            }else{
                $p_data['mid'] = '';
            }
            //时间
            if ($p_data['starttime'] !== '') {
                $starttime = strtotime($p_data['starttime']);
            } else {
                $starttime = 0;
            }
            if ($p_data['endtime'] !== '') {
                $endtime = strtotime($p_data['endtime']) + 86400;
            } else {
                $endtime = strtotime(date('Y-m-d H:i:s')) + 86400;
            }
        } else {
            $p_data['code'] = '';
            $p_data['get_scr'] = '';
            $p_data['mid'] = '';
            $starttime = 0;
            $endtime = strtotime(date('Y-m-d H:i:s')) + 86400;
        }
        $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');

        $CardMember = new CardMember();

        $card_id = $CardMember->where(['top_mid'=>Session::get('login_top_mid')])->value('card_id');
        $map['card_id'] = $card_id;
        $CardUserUpdate = new CardUserUpdate();
        $map['add_bonus|del_bonus'] = ['neq',0];
        $bonus['put'] = $CardUserUpdate->where($map)->sum('add_bonus');

        $bonus['use'] = $CardUserUpdate->where($map)->sum('del_bonus');
//        var_dump($CardUserUpdate->getLastSql());
        $bonus['sur'] = $bonus['put'] - $bonus['use'];
//        var_dump($CardUserUpdate->getLastSql());


//        $map['add_bonus|del_bonus'] = ['neq',0];
        $list = $CardUserUpdate->where($map)->order('id desc')->paginate('20',false,['query' => request()->param()]);
//        var_dump($CardUserUpdate->getLastSql());
        $this->assign('list',$list);
        $this->assign('p_data',$p_data);
        $this->assign('bonus',$bonus);
        $this->get_machlist();
        return $this->fetch();
    }

    //退卡数据
    public function carddellistold(){
        $p_data = request()->get();
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            if ($p_data['nickname']) {
                $map['nickname'] = array('like', '%' . trim($p_data['nickname']) . '%');
            } else {
                $p_data['nickname'] = '';
            }
            if ($p_data['code']) {
                $map['code|phone|old_code'] = array('like', '%' . trim($p_data['code']) . '%');
            } else {
                $p_data['code'] = '';
            }
            if ($p_data['fire']) {
                $map['fire'] = $p_data['fire'];
            } else {
                //激活状态
                if (isset($p_data['fire'])){
                    if ($p_data['fire'] == 0 && $p_data['fire'] <> ''){
                        $map['fire'] = 0;
                    }
                }
                //END
                $p_data['fire'] = '';
            }
            //积分筛选
            if ($p_data['bonus_scr']){
                $ord['bonus'] = $p_data['bonus_scr'] ==1 ? 'desc' : 'asc';
            }else{
                $p_data['bonus_scr'] = '';

            }
            //余额筛选
            if ($p_data['balance_scr']){
                $ord['balance'] = $p_data['balance_scr'] ==1 ? 'desc' : 'asc';
            }else{
                $p_data['balance_scr'] = '';
            }
            //时间筛选
            if ($p_data['get_scr']){
                $ord['create_time'] = $p_data['get_scr'] ==1 ? 'asc' : 'desc';
            }else{
                $p_data['get_scr'] = '';
            }
            $ord['id'] = 'desc';
        } else {
            $p_data['nickname'] = '';
            $p_data['code'] = '';
            $p_data['fire'] = '';
            $p_data['bonus_scr'] = '';
            $p_data['balance_scr'] = '';
            $p_data['get_scr'] = '';
            $ord['id'] = 'asc';
        }
        $CardMember = new CardMember();
        $CardUserGet = new CardUserGet();
        $card_id = $CardMember->where(['top_mid'=>Session::get('login_top_mid')])->value('card_id');
        $map['card_id'] = $card_id;
        $map['card_type'] = 'MEMBER_CARD';
        $map['have'] = 0;
        $card = $CardMember->where(['card_id'=>$card_id])->find();
        $list = $CardUserGet->where($map)->order($ord)->order('del_time desc')->paginate('20',false,['query' => request()->param()]);
        $this->assign('list',$list);
        $this->assign('p_data',$p_data);
        $this->assign('card',$card);
        $this->get_machlist();
        return $this->fetch();
    }

    //操作数据
    public function cardoperlogold(){
        $p_data = request()->get();
        unset($p_data['page']);
        $map = [];
        if ($p_data) {
            if ($p_data['code']) {
                $map['code'] = array('like', '%' . trim($p_data['code']) . '%');
            } else {
                $p_data['code'] = '';
            }
            //门店
            if ($p_data['mid']){
                $map['mid'] = $p_data['mid'];
            }else{
                $p_data['mid'] = '';
            }
            //时间
            if ($p_data['starttime'] !== '') {
                $starttime = strtotime($p_data['starttime']);
            } else {
                $starttime = 0;
            }
            if ($p_data['endtime'] !== '') {
                $endtime = strtotime($p_data['endtime']) + 86400;
            } else {
                $endtime = strtotime(date('Y-m-d H:i:s')) + 86400;
            }
        } else {
            $p_data['code'] = '';
            $p_data['con_username'] = '';
            $p_data['mid'] = '';
            $starttime = 0;
            $endtime = strtotime(date('Y-m-d H:i:s')) + 86400;
        }
        $map['create_time'] = array('between', '' . $starttime . ',' . $endtime . '');
        $CardMember = new CardMember();
        $CardUserUpdate = new CardUserUpdate();
        $card_id = $CardMember->where(['top_mid'=>Session::get('login_top_mid')])->value('card_id');
        $map['card_id'] = $card_id;
        $list = $CardUserUpdate->where($map)->order('id desc')->paginate('20',false,['query' => request()->param()]);
        $this->assign('list',$list);
        $this->assign('p_data',$p_data);
        $this->get_machlist();
        return $this->fetch();
    }

    //门店列表
    private function get_machlist(){
        //门店
        $Merchant = new Merchant();
        $mab['id'] = ['in',$this->get_mer_mid()];
        $mach = $Merchant->where($mab)->select();
        $this->assign('mach',$mach);
    }
    //门店列表
    private function get_machlistold(){
        //门店
        $Merchant = new Merchant();
        $mab['id'] = ['in',$this->get_mer_mid()];
        $mach = $Merchant->where($mab)->select();
        $this->assign('mach',$mach);
    }


    //微信API参数 根据mid获取
    public function option($mid)
    {
        Session::set('openid', null);
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $Merchant = new Merchant();
        $merchantinfo = $Merchant->where('id', $mid)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        Session::set('openid', null);
        $CardMember = new CardMember();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $map['id'] = $CardMember->where('card_id', $card_id)->value('mid');
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->find();
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}
